package com.scuthnweb.dao.impl;

import java.sql.SQLException;
import java.util.List;

import org.hibernate.FlushMode;
import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.springframework.orm.hibernate3.HibernateCallback;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;

import com.scuthnweb.dao.TopDao;
import com.scuthnweb.domain.Top;

public class TopDaoImpl extends HibernateDaoSupport implements TopDao{

	@Override
	public void create(Top top) {
		this.getHibernateTemplate().save(top);
	}

	@Override
	public void update(final Top top) {
		this.getHibernateTemplate().execute(
				new HibernateCallback() {
					public Object doInHibernate(Session session) throws HibernateException,
					SQLException {
						session.setFlushMode(FlushMode.AUTO); 
						session.update(top); 
						session.flush(); 
						return null; 
					}
				});			
	}

	@Override
	public void delete(final Top top) {
		this.getHibernateTemplate().execute(
				new HibernateCallback() {
					@Override
					public Object doInHibernate(Session session) throws HibernateException, SQLException {
						session.setFlushMode(FlushMode.AUTO);
						session.beginTransaction();
						Query query = session.createSQLQuery("DELETE FROM top WHERE id=?")
								.setInteger(0, top.getId() );
						query.executeUpdate();					
						session.getTransaction().commit();
						return null; 
					}
				});		
	}

	@Override
	public List findByCategory(String category) {
        String hql = "FROM Top t WHERE t.category=? ORDER BY t.id DESC";
		return this.getHibernateTemplate().find(hql, new Object[]{category});		
	}

}
